﻿namespace LogManager.Core.Models
{
    using LogManager.Core.Helpers;
    using LogManager.Core.Models.Smtp;
    using LogManager.Utils.Unity;
    using LogManager.Utils.Xml;
    using System.Xml.Linq;
    using LogManager.Core.Factories;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class Settings : XmlElementBase, ISettings
    {
        public const string DEFAULT_TEMPLATE = @"  <Settings>" + SmtpSettings.DEFAULT_TEMPLATE + "</Settings>";

        public SmtpSettings SmtpSettings { get; private set; }
        public readonly IXmlElementFactory _xmlFactory;

        public Settings(XElement baseNode, IXmlElementFactory xmlFactory)
            : base(baseNode)
        {
            this._xmlFactory = xmlFactory;
            this.Initialize();
            this.PropertyChanged += (a, b) => SaveChanges();
        }

        private void Initialize()
        {
            var xml = new XmlResolver<Settings>(BaseNode);
            this.SmtpSettings = xml.ResolveChild(c => c.SmtpSettings, this._xmlFactory.CreateSmtpSettings);
        }

        public override void SaveChanges()
        {
            var xml = new XmlResolver<Settings>(BaseNode);
            xml.SetChild(c => c.SmtpSettings, SmtpSettings);
        }

        ISmtpSettings ISettings.SmtpSettings
        {
            get { return this.SmtpSettings; }
        }
    }
}
